<template>
  <div class="chinese-herb-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>中药材管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">新增药材</el-button>
            <el-button @click="loadData">刷新</el-button>
          </div>
        </div>
      </template>

      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="药材名称">
            <el-input v-model="searchForm.herbName" placeholder="请输入药材名称" />
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="searchForm.categoryId" placeholder="请选择分类" style="width: 120px;" clearable>
              <el-option
                  v-for="category in categoryList"
                  :key="category.categoryId"
                  :label="category.categoryName"
                  :value="category.categoryId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="herbId" label="ID" width="80" />
        <el-table-column prop="herbName" label="药材名称" />
        <el-table-column prop="pinyinName" label="拼音名" />
        <el-table-column prop="categoryName" label="分类" />
        <el-table-column prop="nature" label="性" />
        <el-table-column prop="taste" label="味" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
                size="small"
                :type="row.status === 'available' ? 'warning' : 'success'"
                @click="handleStatusChange(row)"
            >
              {{ row.status === 'available' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pageParams.page"
            v-model:page-size="pageParams.pageSize"
            :total="total"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
            layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { chineseHerbApi, herbCategoryApi } from '@/api/admin'

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const categoryList = ref([])
const total = ref(0)

const searchForm = reactive({
  herbName: '',
  categoryId: null
})

const pageParams = reactive({
  page: 1,
  pageSize: 10
})

// 加载药材数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await chineseHerbApi.page(
        searchForm.herbName,
        searchForm.categoryId,
        pageParams.page,
        pageParams.pageSize
    )
    tableData.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error('加载药材数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const res = await herbCategoryApi.getTree()
    // 将树形结构展平
    const flattenCategories = (categories) => {
      let result = []
      categories.forEach(cat => {
        result.push({
          categoryId: cat.categoryId,
          categoryName: cat.categoryName
        })
        if (cat.children) {
          result = result.concat(flattenCategories(cat.children))
        }
      })
      return result
    }
    categoryList.value = flattenCategories(res.data || [])
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const handleSearch = () => {
  pageParams.page = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    herbName: '',
    categoryId: null
  })
  pageParams.page = 1
  loadData()
}

const handleAdd = () => {
  router.push('/admin/chinese-herb/add')
}

const handleEdit = (row) => {
  console.log("=== 编辑按钮点击调试信息 ===")
  console.log("row 数据:", row)
  console.log("herbId:", row.herbId)
  router.push(`/admin/chinese-herb/edit/${row.herbId}`)
}

const handleStatusChange = async (row) => {
  try {
    const action = row.status === 'available' ? '禁用' : '启用'
    await ElMessageBox.confirm(
        `确定要${action}药材"${row.herbName}"吗？`,
        '提示',
        {type: 'warning'}
    )

    const newStatus = row.status === 'available' ? 'unavailable' : 'available'
    await chineseHerbApi.updateStatus(newStatus, row.herbId)
    ElMessage.success(`${action}成功`)
    loadData()
  } catch (error) {
    // 用户取消操作
  }
}

const getStatusTagType = (status) => {
  const statusMap = {
    available: 'success',
    unavailable: 'danger',
    restricted: 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    available: '启用',
    unavailable: '禁用',
    restricted: '限制'
  }
  return statusMap[status] || status
}

const handlePageChange = () => {
  loadData()
}

const handleSizeChange = () => {
  pageParams.page = 1
  loadData()
}

// 页面挂载时加载数据
onMounted(() => {
  loadData()
  loadCategories()
})
</script>

<style scoped>
.chinese-herb-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
